package xj.toolkit.netty.initializer;

import javax.net.ssl.SSLEngine;

import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;
import xj.toolkit.netty.handler.codec.http.HttpRequestHandler;
import xj.toolkit.netty.handler.codec.http.ssl.HttpSslContextFactory;

public class HttpServerInitializer extends SslBaseInitializer {
	private HttpRequestHandler httpRequestHandler;
	// 一个HTTP请求提交的最大数据量,默认为1M
	private int maxContentLength = 1024 * 1024;

	private HttpSslContextFactory httpSslContextFactory;

	@Override
	public void addCodecHandler(ChannelPipeline pipeline) throws Exception {

		if (httpSslContextFactory.isUseSsl()) {
			SSLEngine engine = httpSslContextFactory.getServerSslContext().newEngine(pipeline.channel().alloc());
			// 说明是服务器端SslContext
			engine.setUseClientMode(false);
			
			// -- 单向认证
			engine.setNeedClientAuth(false);
			pipeline.addLast("ssl", new SslHandler(engine));
		}

		// HttpServerCodec是非线程安全的,不能所有Channel使用同一个
		HttpServerCodec httpServerCodec = new HttpServerCodec();
		pipeline.addLast("codec", httpServerCodec).addLast("aggregator", new HttpObjectAggregator(maxContentLength));
	}

	@Override
	protected void addBusinessHandler(ChannelPipeline pipeline) throws Exception {
		pipeline.addLast("handler", httpRequestHandler);
	}

	public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) {
		this.httpRequestHandler = httpRequestHandler;
	}

	public int getMaxContentLength() {
		return maxContentLength;
	}

	public void setMaxContentLength(int maxContentLength) {
		this.maxContentLength = maxContentLength;
	}

	public HttpSslContextFactory getHttpSslContextFactory() {
		return httpSslContextFactory;
	}

	public void setHttpSslContextFactory(HttpSslContextFactory httpSslContextFactory) {
		this.httpSslContextFactory = httpSslContextFactory;
	}

}
